import subprocess
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import os
from utils.helpers import get_today_date
import math  # 新增导入math模块


def wrap_text(text, font, max_width, draw, font_size):
    """
    自动换行函数。
    :param text: 文本内容
    :param font: 字体
    :param max_width: 最大宽度
    :param draw: ImageDraw 对象
    :param font_size: 字体大小
    :return: 换行后的文本行列表
    """
    lines = []
    paragraphs = text.split('\n')  # 按段落分割
    for paragraph in paragraphs:
        if paragraph.strip() == "":  # 如果是空行，直接添加到 lines
            lines.append("")
            continue
        current_line = ""
        for word in paragraph.split():
            # 检查当前行加上新单词是否会超出最大宽度
            test_line = current_line + word + " "
            test_width = draw.textlength(test_line, font=font)
            if test_width <= max_width:
                current_line = test_line
            else:
                # 如果当前行不为空，先保存当前行
                if current_line:
                    lines.append(current_line.strip())
                # 如果单词本身超出最大宽度，强制换行
                if draw.textlength(word, font=font) > max_width:
                    # 将长单词拆分成多个部分
                    for i in range(0, len(word), max_width // font_size):
                        lines.append(word[i:i + max_width // font_size])
                else:
                    current_line = word + " "
        # 保存最后一行
        if current_line:
            lines.append(current_line.strip())
    return lines


def generate_images_with_background(txt_file_path, output_dir, background_image_path, watermark_image_path):
    """
    将TXT文件转换为图片，并添加背景图。
    :param txt_file_path: TXT文件路径
    :param output_dir: 图片输出目录
    :param background_image_path: 背景图片路径
    :return: 生成的图片目录路径
    """
    # 读取TXT文件内容
    with open(txt_file_path, "r", encoding="utf-8") as file:
        story = file.read()

    # 创建输出目录
    base_name = os.path.splitext(os.path.basename(txt_file_path))[0]
    output_path = os.path.join(output_dir, base_name)
    os.makedirs(output_path, exist_ok=True)

    # 图片生成逻辑
    font_path = "/System/Library/AssetsV2/com_apple_MobileAsset_Font7/b86e58f38fd21e9782e70a104676f1655e72ebab.asset/AssetData/Yuanti.ttc"
    font_size = 45
    image_width = 1000
    image_height = 1420
    margin = 50
    max_width = image_width - 2 * margin

    # 加载背景图片
    background = Image.open(background_image_path)
    # 调整背景图片大小以适应画布
    background = background.resize((image_width, image_height))
    # 虚化背景图片
    background = background.filter(ImageFilter.GaussianBlur(radius=10))
    # 调整背景图片透明度（颜色变浅）
    background = background.convert("RGBA")
    background = Image.blend(Image.new("RGBA", background.size, (255, 255, 255, 200)), background, alpha=0.5)

    # 创建临时图片和 draw 对象用于计算文本宽度
    temp_image = Image.new('RGB', (image_width, image_height), color=(255, 255, 255))
    temp_draw = ImageDraw.Draw(temp_image)
    temp_font = ImageFont.truetype(font_path, font_size)

    # 自动换行
    lines = wrap_text(story, font=temp_font, max_width=max_width, draw=temp_draw, font_size=font_size)

    # 加载水印图片并调整大小（添加透明度调整）
    watermark = Image.open(watermark_image_path).convert("RGBA")
    watermark_size = (120, 120)
    watermark = watermark.resize(watermark_size)
    watermark = watermark.point(lambda p: p * 0.7)  # 添加70%透明度

    # 分页
    # 分页（调整为18行以适应动态元素）
    max_lines_per_page = 18  # 从20调整为18
    pages = []
    current_page = []
    for line in lines:
        current_page.append(line)
        if len(current_page) >= max_lines_per_page:
            pages.append(current_page)
            current_page = []
    # 添加最后一页（如果有剩余行）
    if current_page:
        pages.append(current_page)

    # 生成每页图片（改为生成GIF）
    today_date = get_today_date()
    total_pages = len(pages)

    # 动画参数设置
    num_frames = 10  # 总帧数
    duration = 150  # 每帧持续时间（毫秒）
    wave_amplitude = 100  # 水印波动幅度

    for i, page in enumerate(pages):
        frames = []  # 存储动画帧

        for frame_num in range(num_frames):
            # 创建画布
            frame = Image.new('RGB', (image_width, image_height), color=(255, 255, 255))
            frame.paste(background, (0, 0))
            draw = ImageDraw.Draw(frame)
            font = ImageFont.truetype(font_path, font_size)

            # 绘制正文内容（保持不变）
            y = margin
            for line in page:
                if line == "":
                    y += font_size + 10
                else:
                    draw.text((margin, y), line, font=font, fill=(0, 0, 0))
                    y += font_size + 10

            # 绘制固定元素（页码和声明）
            # 页码
            page_number_text = f"{i + 1}/{total_pages}"
            number_font = ImageFont.truetype(font_path, 30)
            text_width = draw.textlength(page_number_text, font=number_font)
            draw.text(
                (image_width - margin - text_width, image_height - margin - 100),
                page_number_text,
                font=number_font,
                fill=(100, 100, 100)
            )

            # 声明文字
            disclaimer_text = "本故事纯属虚构，如有雷同纯属巧合"
            disclaimer_font = ImageFont.truetype(font_path, 30)
            text_width = draw.textlength(disclaimer_text, font=disclaimer_font)
            draw.text(
                ((image_width - text_width) // 2, image_height - margin - 60),
                disclaimer_text,
                font=disclaimer_font,
                fill=(100, 100, 100)
            )

            # 计算动态水印位置（正弦波动）
            phase = 2 * math.pi * frame_num / num_frames
            x_offset = int(wave_amplitude * math.sin(phase))
            base_x = (image_width - watermark_size[0]) // 2  # 居中基准位置
            base_y = image_height - watermark_size[1] - margin - 150

            # 应用动态偏移
            watermark_position = (
                base_x + x_offset,
                base_y + int(wave_amplitude / 4 * math.cos(phase))  # 添加垂直方向波动
            )

            # 粘贴水印（保持透明度）
            frame.paste(watermark, watermark_position, mask=watermark)

            frames.append(frame.copy())

        # 保存为GIF文件
        image_filename = f"{base_name}_part_{i + 1}.gif"
        frames[0].save(
            os.path.join(output_path, image_filename),
            save_all=True,
            append_images=frames[1:],
            duration=duration,
            loop=0,  # 无限循环
            optimize=True  # 启用优化
        )

    return output_path
